local yy `1'

*drop predicted stocks and depvar from previous year (if yy > 1996)
cap drop pred
cap drop kdepvar

* predict the dep-var response in yy+2 using the regression in 1.a, shift it to 1997-2011
predict pred
replace pred = 0 if pred == . & year <= 2009
bys firm_division ctryid (year) : gen Lpred = pred[_n-2] if _n > 2
replace pred = Lpred
drop Lpred

*remove the predicted value from the last iteration in yy+2
* and replace it with the predicted value + some noise
replace pdepvar = . if year == `yy'+2
replace pdepvar = rpoisson(pred) if year == `yy'+2 & ctryid == 1 

* Stata messes up poisson if mean=0; we replace it here. 
replace pdepvar = 0 if pred == 0 & year == `yy'+2 & ctryid == 1 

* expand depvar-counts across countries (firm-div-year-ctry-level data) 
bysort firm_division : egen _pdepvar = min(pdepvar) if year == `yy'+2 
replace pdepvar = _pdepvar if year == `yy'+2
drop _pdepvar

**Setting the stock
*put current flow of patents as uncalculated "stock"
gen kdepvar=pdepvar
*set the correct initial stock of patents k0 
replace kdepvar = k0 if year == 1995 
*compute a firms stock of patents
bysort firm_division ctryid (year): replace kdepvar=kdepvar+ $deltadepreciation * kdepvar[_n-1] if _n>1